package com.awesome.common.util.file;

import android.util.Base64;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * Author: JFangZ
 * Email: janezhang1901@163.com
 * Date: 2020/11/17 16:26
 * Description:编解码工具类
 */
public class EncodeUtil {
    /**
     * Author: JFangZ
     * Email: janezhang1901@163.com
     * Date:2020/11/17 18:20
     * Description:URL 编码
     */
    public static String urlEncode(String string) {
        try {
            return URLEncoder.encode(string, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return string;
    }

    /**
     * Author: JFangZ
     * Email: janezhang1901@163.com
     * Date:2020/11/17 18:20
     * Description:URL 解码
     */
    public static String urlDecode(String string) {
        try {
            return URLDecoder.decode(string, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return string;
    }

    /**
     * Author: JFangZ
     * Email: janezhang1901@163.com
     * Date:2020/11/17 18:39
     * Description:base64 编码,重载 {@link #base64Encode(byte[], int, String)}
     */
    public static String base64Encode(byte[] bytes) {
        return base64Encode(bytes, Base64.DEFAULT, "");
    }

    /**
     * Author: JFangZ
     * Email: janezhang1901@163.com
     * Date:2020/11/17 18:39
     * Description:base64 编码,重载 {@link #base64Encode(byte[], int, String)}
     */
    public static String base64Encode(byte[] bytes, int flag) {
        return base64Encode(bytes, flag, "");
    }

    /**
     * Author: JFangZ
     * Email: janezhang1901@163.com
     * Date:2020/11/17 18:39
     * Description:base64 编码,重载
     *
     * @param bytes  待编码的数据
     * @param header 需添加的头部
     * @return base64 编码后的数据
     */
    public static String base64Encode(byte[] bytes, int flag, String header) {
        return header + Base64.encodeToString(bytes, flag);
    }

    /**
     * Author: JFangZ
     * Email: janezhang1901@163.com
     * Date:2020/11/17 18:39
     * Description:base64 解码
     *
     * @param base64 待解码的数据,没有 data:x/x;base64, 这样的头部
     * @return 解码后的二进制数组
     */
    public static byte[] base64Decode(String base64) {
        return base64Decode(base64, Base64.DEFAULT);
    }

    /**
     * Author: JFangZ
     * Email: janezhang1901@163.com
     * Date:2020/11/17 18:39
     * Description:base64 解码
     *
     * @param base64 待解码的数据,没有 data:x/x;base64, 这样的头部
     * @return 解码后的二进制数组
     */
    public static byte[] base64Decode(String base64, int flag) {
        return Base64.decode(base64, flag);
    }
}
